<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Admin\Model;

use Think\Model\RelationModel;
/**
 * Description of GoodsModel
 *
 * @author Administrator
 */
class GoodsModel  extends RelationModel {
    //put your code here
    
    protected  $tableName = 'goods';
    
    protected $_auto = array ( 
        array('ctime','time',1,'function'), 
        array('user_id','getUserId',3,'callback')
    );
    
    protected $_link = array(
        'goods_type'=>array(
            'mapping_type' => self::BELONGS_TO,
            'class_name' => 'goods_type',
            'mapping_name'=>'goods_type',
            'foreign_key'=>'goods_type',
            'parent_key'  => 'id'
        ),
        'goods_spec'=>array(
            'mapping_type' => self::HAS_MANY,
            'class_name' => 'goods_spec',
            'mapping_name'=>'goods_spec',
            'foreign_key'=>'goods_id',
            'parent_key'  => 'id'
        )
    );
    
    public function getUserId(){
        return session('userId');
    }
    
    public function getGoodsList($where=[],$limit=10,$needPage=true){
        
        if($needPage){
            $count = $this->where($where)->count();
            $p = getPage($count,$limit);
            $data = $this->relation(true)->where($where)->limit($p->firstRow, $p->listRows)->order('ctime desc')->select();
            return array('data'=>$data,'page'=>$p->show());
        }else{
            $data = $this->relation(true)->where($where)->order('ctime desc')->select();
            return array('data'=>$data);
        }
        
        
    }
    
    public function getGoodsInfoById($id,$spec_id){
        $this->where("id = ".$id)->setInc('click'); 
        $data = $this->relation(true)->where("id = ".$id)->find();
        $data['goods_tags'] = explode("|", $data['goods_tags']);
        if(!empty($spec_id)){
            foreach($data['goods_spec'] as $v){
                if($v['id'] == $spec_id){
                    $goods_spec = $v;
                }
            }
            $data['goods_spec'] = $goods_spec;
        
            $data['price'] = $goods_spec['spec_price'];
            $data['integral'] = $goods_spec['spec_integral'];
            $data['goods_imgs'] = $goods_spec['spec_img'];
            
        }
        return $data;
    }
    

}
